import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer ,Modal ,FormInstance} from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage,connect,ConnectProps } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import AreaTree from './components/AreaTree';

import type { TableListItem } from './data.d';
import { queryData, updateData, addData, removeData,updateStatus } from './service';

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addData({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在配置');
  try {
    await updateData({
      name: fields.name,
      short_name: fields.short_name,
      order_by: fields.order_by,
      remark: fields.remark,
      id: fields.id,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeData({
      ids: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const handleRemoveOne = async (selectedRow: TableListItem) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    let params = [selectedRow.id]
    await removeData({
      ids: params,
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const handleUpdateStatus = async (id:string,status:string) => {
  const hide = message.loading('正在更新状态');
  try {
    await updateStatus(id,status);
    message.success('状态更新成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('状态更新失败，请重试');
    return false;
  }
};

export type GlobalTableProps = {
  currentUser?: CurrentUser;
} & Partial<ConnectProps>;

const TableList: React.FC<GlobalTableProps> = (props) => {
  const formTableRef = useRef<FormInstance>();
  const formRef = useRef<FormInstance>();
  const childref = useRef();

  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  
  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  //选中树形
  const [selectArea, setSelectArea] = useState<any>();

  const { currentUser } = props;

  /** 国际化配置 */
  const intl = useIntl();

  const columns: ProColumns<TableListItem>[] = [
    {
      title: (
        <FormattedMessage
          id="地区名称"
          defaultMessage="地区名称"
        />
      ),
      dataIndex: 'name',
      tip: '地区名称',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: <FormattedMessage id="地区简称" defaultMessage="地区简称" />,
      dataIndex: 'short_name',
      valueType: 'textarea',
    },
    {
      title: <FormattedMessage id="状态" defaultMessage="状态" />,
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: (
            <FormattedMessage id="启用" defaultMessage="启用" />
          ),
          status: 'Success',
        },
        1: {
          text: (
            <FormattedMessage id="禁用" defaultMessage="禁用" />
          ),
          status: 'Processing',
        },
      },
    },
    {
      title: <FormattedMessage id="排序" defaultMessage="排序" />,
      dataIndex: 'order_by',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="父级id" defaultMessage="父级id" />,
      dataIndex: 'parent_id',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: true,
    },
    {
      title: <FormattedMessage id="创建时间" defaultMessage="创建时间" />,
      dataIndex: 'create_time',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      width:'220px',
      valueType: 'option',
      render: (_, record) => [
         <Button type="primary" size='small' key="config"
         style={{ display: currentUser?.authButton.includes('area:edit') ? 'block' : 'none' }}
         onClick={() => {
           record.parent_name = selectArea.name;
           record.parent_id = selectArea.id;
           handleUpdateModalVisible(true);
           setCurrentRow(record);
         }}>
         编辑
       </Button>,
        <Button type="primary" size='small' danger 
          style={{ display: currentUser?.authButton.includes('area:del') ? 'block' : 'none' }}
          onClick={async () => {
          Modal.confirm({
            title: '删除任务',
            content: '确定删除该任务吗？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
              const success = handleRemoveOne(record);
              if (success) {
                if (actionRef.current) {
                  actionRef.current.reload();
                }
                childref.current._childFn();
              }
            },
          });
        }}>
        删除
      </Button>,
     <Button type="primary" size='small' style={{display: (record.status=='0' && currentUser?.authButton.includes('area:status')) ?'block':'none'}} danger onClick={() => {
        const success = handleUpdateStatus(record.id,'1');
        if (success) {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      }}>
      禁用
    </Button>,
     <Button type="primary" size='small' style={{display: (record.status=='1' && currentUser?.authButton.includes('area:status')) ?'block':'none'}} onClick={() => {
      const success = handleUpdateStatus(record.id,'0');
        if (success) {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
    }}>
    启用
  </Button>,
      ],
    },
  ];

  return (
      <PageContainer>
      <div style={{ width: '20%', float:'left' }}>
        <AreaTree myFef={childref} onSelect={async (value:any) => {
          setSelectArea(value);
          //查询列表数据
          if (actionRef.current) {
            formTableRef.current.setFieldsValue({
              parent_id: value.id
            });
            formTableRef.current.submit();
          }
          }}></AreaTree>
      </div>
      <div style={{ width: '79%', float:'right' }}>
      <ProTable<TableListItem>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: '地区信息',
        })}
        actionRef={actionRef}
        formRef={formTableRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            style={{ display: currentUser?.authButton.includes('area:add') ? 'block' : 'none' }}
            onClick={() => {
              if(selectArea.id==''||selectArea.id==null){
                message.warning('请选择左侧父级节点');
              }else{
                formRef.current.setFieldsValue({
                  parent_name: selectArea.name,
                });
                handleModalVisible(true);
              }
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
          </Button>,
        ]}
        request={
          (params,sorter,filter) => queryData({...params,parent_id:selectArea.id}).then(res =>{
            const result = {
              data:res.data.rows,
              total:res.data.total,
              success:true
            }
            return result
          })
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      </div>
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            style={{ display: currentUser?.authButton.includes('area:del') ? 'block' : 'none' }}
            onClick={async () => {
              Modal.confirm({
                title: '删除任务',
                content: '确定删除该任务吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  const success = handleRemove(selectedRowsState);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                    childref.current._childFn();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: '新建地区',
          defaultMessage: '新建地区',
        })}
        width="600px"
        formRef={formRef}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd({...value,parent_id:selectArea.id,level_num:selectArea.level_num,area_cascade:selectArea.area_cascade} as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            formRef.current?.resetFields();
            childref.current._childFn();
          }
        }}
      >
          <ProFormText
          label={intl.formatMessage({
            id: '父节点名称',
            defaultMessage: '父节点名称',
          })}
          disabled
          width="xl"
          name="parent_name"
          placeholder="请输入父节点名称"
        />
        <ProFormText
          label={intl.formatMessage({
            id: '地区名称',
            defaultMessage: '地区名称',
          })}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="地区名称"
                  defaultMessage="地区名称"
                />
              ),
            },
          ]}
          width="xl"
          name="name"
          placeholder="请输入地区名称"
        />
        <ProFormText
          label={intl.formatMessage({
            id: '地区简称',
            defaultMessage: '地区简称',
          })}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="地区简称"
                  defaultMessage="地区简称"
                />
              ),
            },
          ]}
          width="xl"
          name="short_name"
          placeholder="请输入地区简称"
        />
        <ProFormText
          label={intl.formatMessage({
            id: '排序',
            defaultMessage: '排序',
          })}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="排序"
                  defaultMessage="排序"
                />
              ),
            },
          ]}
          width="xl"
          name="order_by"
          placeholder="请输入排序"
        />
        <ProFormTextArea width="xl" name="remark" label={intl.formatMessage({
            id: '备注',
            defaultMessage: '备注',
          })}
          placeholder="请输入备注"
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
           const success = await handleUpdate({...value,id:currentRow?.id});
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            childref.current._childFn();
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

// export default TableList;
export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
}))(TableList);
